//
//  CarDetailViewController.m
//  MonitoringNetwork
//
//  Created by admin on 2017/12/7.
//  Copyright © 2017年 wtmcxlm. All rights reserved.
//

#import "CarDetailViewController.h"
#import "MineViewController.h"
#import "CarDetailListCell.h"
#import "MJRefresh.h"
@interface CarDetailViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView *carDetailTableView;
@property (nonatomic,strong)UITextField *searchTextFile;
@property (nonatomic,strong)NSMutableArray *dataDetaliListArrar;
@property (nonatomic,assign)NSInteger index;
@property (nonatomic,strong)LoadNetView *loadNetView;
@property (nonatomic, strong) NSMutableArray *heightArray;

@end

static NSString *CarDetaileCellID = @"CarDetaileCellID";
@implementation CarDetailViewController
- (LoadNetView *)loadNetView
{
    if (!_loadNetView) {
        _loadNetView = [LoadNetView new];
        [self.view addSubview:_loadNetView];
        [_loadNetView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.centerY.mas_equalTo(self.view);
        }];
        _loadNetView.hidden = NO;
    }
    return _loadNetView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavigationTitleWithTitle:@"车辆详情"];
    [self loadUI];
    [self loadcarDetailTableView];
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipemethod:)];
    swipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swipe];
}
- (void)swipemethod:(UISwipeGestureRecognizer *)swipe
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 懒加载
- (void)loadcarDetailTableView
{
        _carDetailTableView = [UITableView new];
        _carDetailTableView.delegate = self;
        _carDetailTableView.dataSource = self;
//        _carDetailTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _carDetailTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [_carDetailTableView registerClass:[CarDetailListCell class] forCellReuseIdentifier:CarDetaileCellID];
        _carDetailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_carDetailTableView];
        [_carDetailTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(self.view);
            make.top.mas_equalTo(self.view.mas_top).offset(NavationBarHeight+kHeightOfPt(176));
        }];
}


- (void)loadUI
{
    //设置导航栏返回按钮
    UIView *leftContentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
    UIButton *letfButton = [[UIButton alloc] initWithFrame:leftContentView.bounds];
    [letfButton setBackgroundImage:[UIImage imageNamed:@"backNormal"] forState:UIControlStateNormal];
    [letfButton setBackgroundImage:[UIImage imageNamed:@"backSel"] forState:UIControlStateHighlighted];
    [letfButton addTarget:self action:@selector(leftItemBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [leftContentView addSubview:letfButton];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftContentView];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UIView *rightContentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
    UIButton *rightButton = [[UIButton alloc] initWithFrame:rightContentView.bounds];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"personNormal"] forState:UIControlStateNormal];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"personSel"] forState:UIControlStateHighlighted];
    [rightButton addTarget:self action:@selector(rightItemBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [rightContentView addSubview:rightButton];
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightContentView];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    UIView *searchView = [UIView new];
    searchView.backgroundColor = [UIColor whiteColor];
    searchView.layer.cornerRadius = kWidthOfPt(5);
    searchView.clipsToBounds = YES;
    searchView.layer.borderWidth = kWidthOfPt(2);
    searchView.layer.borderColor = [UIColor colorWithRed:0.80f green:0.80f blue:0.80f alpha:1.00f].CGColor;
    [self.view addSubview:searchView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.view.mas_top).offset(NavationBarHeight + kHeightOfPt(176)*0.5);
        make.left.mas_equalTo(self.view.mas_left).offset(kWidthOfPt(129));
        make.height.mas_equalTo(35);
        make.width.mas_equalTo(kWidthOfPt(672));
    }];
    
    UIImageView *iconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"searchSel"]];
    [searchView addSubview:iconImageView];
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(searchView.mas_left).offset(kWidthOfPt(23));
        make.centerY.mas_equalTo(searchView);
        make.width.mas_equalTo(18);
        make.height.mas_equalTo(18);
    }];
    
    UIButton *searchBtn = [UIButton new];
    [searchBtn addTarget:self action:@selector(searchBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    searchBtn.layer.cornerRadius = kWidthOfPt(5);
    searchBtn.clipsToBounds = YES;
    [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [searchBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [searchBtn setBackgroundColor:[UIColor colorWithRed:0.13f green:0.58f blue:0.88f alpha:1.00f]];
    [self.view addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view.mas_right).offset(-kWidthOfPt(78));
        make.width.mas_equalTo(kWidthOfPt(206));
        make.height.mas_equalTo(35);
        make.centerY.mas_equalTo(searchView);
    }];
    
    UIButton *clearBtn = [UIButton new];
    clearBtn.imageEdgeInsets = UIEdgeInsetsMake(13.0, 26.0,13.0,0.0);
    [clearBtn addTarget:self action:@selector(clearBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [clearBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    [searchView addSubview:clearBtn];
    [clearBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(searchView.mas_right).offset(-kWidthOfPt(23));
        make.centerY.mas_equalTo(searchView);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
    }];
    
    _searchTextFile = [UITextField new];
    _searchTextFile.tintColor = [UIColor colorWithRed:0.36f green:0.36f blue:0.36f alpha:1.00f];
    _searchTextFile.placeholder = @"车牌号/VIN";
    _searchTextFile.delegate = self;
    [self.searchTextFile addTarget:self action:@selector(textFieldTextChange:) forControlEvents:UIControlEventEditingChanged];
    [searchView addSubview:_searchTextFile];
    [_searchTextFile mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(iconImageView.mas_right).offset(kWidthOfPt(20));
        make.right.mas_equalTo(clearBtn.mas_left);
        make.top.bottom.mas_equalTo(searchView);
    }];
}

#pragma mark - 数据加载
-(void)loadDataWithCarUseIn:(NSInteger)CarUseIn
{
    if (!_plate) {
        _plate = @"";
    }
    if (!_deptId) {
        _deptId = @"";
    }
    
    _dataDetaliListArrar = [NSMutableArray array];
    _index = 0;
    [self.loadNetView start];
    NSDictionary *param = @{
                            @"carUseIn":@(CarUseIn),
                            @"pageIndex":@(1),
                            @"pageSize":@(15)
                            };
    [[NetWorkTool sharedNetworkTool] requestWithUrlString:kURL_QueryCarStatus method:@"POST" parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        [_carDetailTableView.mj_header endRefreshing];
        [self.loadNetView endAnimationWithResult:LoadingViewResultTypeSuccess];
        NSLog(@"%@",responseObject);
        if ([responseObject[@"state"] integerValue] == 0) {
            NSArray *useRegionsArr = responseObject[@"obj"][@"content"];
            if (useRegionsArr.count && useRegionsArr) {
                for (NSDictionary *dic in useRegionsArr) {
                    VehicleListModel *model = [VehicleListModel new];
                    [model yy_modelSetWithDictionary:dic];
                    [_dataDetaliListArrar addObject:model];
                }
                [_carDetailTableView reloadData];
            }
        }else{
            
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self.loadNetView endAnimationWithResult:LoadingViewResultTypeError];
        [_carDetailTableView.mj_header endRefreshing];
    }];
    
}
-(void)loadDataWithDeptId:(NSString *)deptId
{
    if (!_plate) {
        _plate = @"";
    }
    if (!_deptId) {
        _deptId = @"";
    }
    
    _dataDetaliListArrar = [NSMutableArray array];
    _index = 0;
    [self.loadNetView start];
    NSDictionary *param = @{
                            @"deptIds":deptId,
                            @"plateNum":_plate,
                            @"pageIndex":@(1),
                            @"pageSize":@(15)
                            };
    [[NetWorkTool sharedNetworkTool] requestWithUrlString:kURL_QueryCarStatus method:@"POST" parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        [_carDetailTableView.mj_header endRefreshing];
        [self.loadNetView endAnimationWithResult:LoadingViewResultTypeSuccess];
        NSLog(@"%@",responseObject);
        if ([responseObject[@"state"] integerValue] == 0) {
            NSArray *useRegionsArr = responseObject[@"obj"][@"content"];
            if (useRegionsArr.count && useRegionsArr) {
                for (NSDictionary *dic in useRegionsArr) {
                    VehicleListModel *model = [VehicleListModel new];
                    [model yy_modelSetWithDictionary:dic];
                    [_dataDetaliListArrar addObject:model];
                }
                [_carDetailTableView reloadData];
            }
        }else{
            
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self.loadNetView endAnimationWithResult:LoadingViewResultTypeError];
        [_carDetailTableView.mj_header endRefreshing];
    }];
    
}

-(void)loadDataWithPlat:(NSString *)plat
{
    if (!_plate) {
        _plate = @"";
    }
    if (!_deptId) {
        _deptId = @"";
    }
    _dataDetaliListArrar = [NSMutableArray array];
    _index = 0;
    [self.loadNetView start];
    NSDictionary *param = @{
                            @"plateNum":plat,
                            @"deptIds":_deptId,
                            @"pageIndex":@(1),
                            @"pageSize":@(15)
                            };
    [[NetWorkTool sharedNetworkTool] requestWithUrlString:kURL_QueryCarStatus method:@"POST" parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(id  _Nullable responseObject) {
         [_carDetailTableView.mj_header endRefreshing];
        [self.loadNetView endAnimationWithResult:LoadingViewResultTypeSuccess];
        NSLog(@"%@",responseObject);
        if ([responseObject[@"state"] integerValue] == 0) {
            NSArray *useRegionsArr = responseObject[@"obj"][@"content"];
            if (useRegionsArr.count && useRegionsArr) {
                for (NSDictionary *dic in useRegionsArr) {
                    VehicleListModel *model = [VehicleListModel new];
                    [model yy_modelSetWithDictionary:dic];
                    [_dataDetaliListArrar addObject:model];
                }
                [_carDetailTableView reloadData];
            }
        }else{
        }
        
    } failure:^(NSError * _Nonnull error) {
         [self.loadNetView endAnimationWithResult:LoadingViewResultTypeError];
         [_carDetailTableView.mj_header endRefreshing];
    }];
   
}
- (void)loadNewData
{
    [self loadDataWithPlat:_plate];
}
- (void)loadMoreData
{
    if (!_plate) {
        _plate = @"";
    }
    if (!_deptId) {
        _deptId = @"";
    }
    [self.loadNetView start];
//    NSMutableArray *tempArr = [NSMutableArray array];
    _index += 1;
    NSDictionary *param = @{
                            @"plateNum":_plate,
                            @"deptIds":_deptId,
                            @"pageIndex":@(_index),
                            @"pageSize":@15
                            };
    [[NetWorkTool sharedNetworkTool] requestWithUrlString:kURL_QueryCarStatus method:@"POST" parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        [self.loadNetView endAnimationWithResult:LoadingViewResultTypeSuccess];
        [_carDetailTableView.mj_footer endRefreshing];
        if ([responseObject[@"state"] integerValue] == 0) {
            NSArray *useRegionsArr = responseObject[@"obj"][@"content"];;
            if (useRegionsArr.count && useRegionsArr) {
                for (NSDictionary *dic in useRegionsArr) {
                    VehicleListModel *model = [VehicleListModel new];
                    [model yy_modelSetWithDictionary:dic];
                    [_dataDetaliListArrar addObject:model];
                }
                 [_carDetailTableView reloadData];
            }

        }else{
            
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self.loadNetView endAnimationWithResult:LoadingViewResultTypeError];
        [_carDetailTableView.mj_footer endRefreshing];
    }];
    
    
}

#pragma mark - 事件监听
- (void)leftItemBtnClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightItemBtnClick:(UIButton *)sender
{
    sender.enabled = NO;
    MineViewController *mineVc = [MineViewController new];
    [mineVc setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:mineVc animated:YES];
    sender.enabled = YES;
}
- (void)backBtnDidClick:(UIButton *)sender
{
}
- (void)searchBtnDidClick:(UIButton *)sender
{
    _plate = self.searchTextFile.text;
    [self loadDataWithPlat:self.searchTextFile.text];
    [self.searchTextFile resignFirstResponder];
    
}
- (void)clearBtnDidClick:(UIButton *)sender
{
    [self.searchTextFile setText:@""];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}


-(void)textFieldTextChange:(UITextField *)textField{
    NSLog(@"textField1 -  %@",textField.text);
//    [self loadDataWithPlat:textField.text];
    
}
#pragma mark - UITableView 数据源 代理

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataDetaliListArrar.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CarDetailListCell *carDetaliCell = [tableView dequeueReusableCellWithIdentifier:CarDetaileCellID];
    if (_dataDetaliListArrar.count) {
        carDetaliCell.model = _dataDetaliListArrar[indexPath.row];
    }
    carDetaliCell.selectionStyle = UITableViewCellSelectionStyleNone;
    return carDetaliCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSNumber *cellHeight = [self.heightArray h_safeObjectAtIndex:indexPath.row];
    if (cellHeight) {
        NSLog(@"不用计算，直接返回行高了");
        return [cellHeight floatValue];
    }else{
        VehicleListModel *model = [VehicleListModel new];
        if (_dataDetaliListArrar.count) {
            model = _dataDetaliListArrar[indexPath.row];
        }
        NSString *status = model.position;
        CGFloat statusHeight = 0;
        if (!status) {
            statusHeight = 11;
        }else{
            statusHeight = [CarDetailListCell tableView:tableView rowHeightForObject:status];
        }
        CGFloat iconHeight = 149-11;
        [self.heightArray addObject:@(statusHeight + iconHeight)];
        NSLog(@"第一次加载计算一次，每次展示都计算一次");
        return statusHeight + iconHeight;
    }
    
}
- (NSMutableArray *)heightArray{
    if (!_heightArray) {
        _heightArray = @[].mutableCopy;
    }
    return _heightArray;
}
    
@end
